/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.common.network;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.content.Context;
import android.text.TextUtils;

import com.mol.market.common.util.Utils;

/**
 * 机锋市场API响应缓存管理器
 * 
 * @author Andrew.Wang
 * @date 2011-5-11
 */
public class ResponseCacheManager {


    private static ResponseCacheManager mInstance;
    
    private final HashMap<String, SoftReference<Object>> mResponseCache = 
        new HashMap<String, SoftReference<Object>>();

    private ResponseCacheManager() {
    }


    public static synchronized ResponseCacheManager getInstance() {
        if (mInstance == null) {
            mInstance = new ResponseCacheManager();
        }
        return mInstance;
    }
    
    /**
     * 从缓存中获取API访问结果
     */

    public Object getResponse(Context context, String key) {

        if (TextUtils.isEmpty(key))
            return null;

        if (mResponseCache == null) {
            return null;
        }
        
        if (!mResponseCache.containsKey(key)) {
            return null;
        }

        Object obj = mResponseCache.get(key).get();

        if (obj == null) {
            obj = getResponseFromSdcard(context, key);
        }
        Utils.D("get response cache " + key);
        return obj;
    }

    /**
     * 缓存API访问结果
     */
    public synchronized void putResponse(Context context, int actionId, String key, Object value) {
        if (mResponseCache != null) {
            if (!mResponseCache.containsKey(key)) {
                saveResponseToSdcard(context, key, value);
            }
            mResponseCache.put(key, new SoftReference<Object>(value));
        }
    }
    
    /**
     * 将API结果缓存到SD卡上
     */
    public static void saveResponseToSdcard(Context context, String key, Object obj) {
        final File cacheDir = context.getCacheDir();
        try {
            FileOutputStream fos = new FileOutputStream(new File(cacheDir, key));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
            oos.close();
        } catch (IOException e) {
            Utils.E("Error when save api cache", e);
        }
        Utils.D("save response cache to sd card " + key);
    }
    
    /**
     * 从SD卡上读取API缓存结果
     */

    public static Object getResponseFromSdcard(Context context, String key) {
        final File cacheDir = context.getCacheDir();
        final File target = new File(cacheDir, key);
        if (target.exists()) {
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(target));
                Object result = ois.readObject();
                ois.close();
                
                Utils.D("read response cache from sd card " + key);
                return result;
            } catch (IOException e) {
                Utils.E("Error when get api cache", e);
            } catch (ClassNotFoundException e) {
                Utils.E("Error when get api cache", e);
            }
        }
        return null;
    }
    
    /**
     * 清除所有API缓存
     */
    public void clear() {
        if (mResponseCache != null) {
            mResponseCache.clear();
        }
        mInstance = null;
    }

}